package com.gfxy.modules.items.controller;

import java.io.IOException;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gfxy.modules.GfxyUtils;
import com.gfxy.modules.common.entity.MemberList;
import com.gfxy.modules.common.entity.MemberSimpleList;
import com.gfxy.modules.common.service.IMemberListService;
import com.gfxy.modules.items.service.DictTranslater;
import com.gfxy.modules.items.vo.*;
import com.gfxy.modules.excel.TemplateUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecg.common.api.vo.Result;

import com.gfxy.modules.items.entity.Tysx;
import com.gfxy.modules.items.service.ITysxService;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.extern.slf4j.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 体育赛项（团体）
 * @Author: jeecg-boot
 * @Date:   2021-10-03
 * @Version: V1.0
 */
@Api(tags="体育赛项（团体）")
@RestController
@RequestMapping("/teaching/tysx")
@Slf4j
public class TysxController {
	 private static final String TEMPLSTE="Template/体育赛项.xls";
	@Autowired
	private ITysxService tysxService;
	@Autowired
	private IMemberListService memberListService;
	 @Autowired
	 private DictTranslater dictTranslater;
	 @Autowired
	 private TemplateUtil templateUtil;
	/**
	 * 分页列表查询
	 *
	 * @param tysx
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "体育赛项（团体）-分页列表查询")
	@ApiOperation(value="体育赛项（团体）-分页列表查询", notes="体育赛项（团体）-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(Tysx tysx,
								   @RequestParam(name = "date") String date,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		String rolesStr = GfxyUtils.getRoles(req);
		IPage<TysxMemberPage> pageList = tysxService.getTysxMemberPageListByYear(date,pageNo,pageSize);
		return Result.OK(pageList);

	}

	 private boolean hasTeachingApprovePermission(String rolesStr){
		 return rolesStr.contains("teaching_approve");
	 }
	 @DeleteMapping(value = "/pass")
	 public Result<?> queryPageList(@RequestParam(name="ids",required=true) String ids) {
		 this.tysxService.passBatch(Arrays.asList(ids.split(",")),"1");
		 return Result.OK("审核成功");
	 }
	 /**
	 *   添加
	 *
	 * @param tysxPage
	 * @return
	 */
	@AutoLog(value = "体育赛项（团体）-添加")
	@ApiOperation(value="体育赛项（团体）-添加", notes="体育赛项（团体）-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody TysxPage tysxPage) {
		Tysx tysx = new Tysx();
		BeanUtils.copyProperties(tysxPage, tysx);
		tysxService.saveMain(tysx, tysxPage.getMemberListList());
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param tysxPage
	 * @return
	 */
	@AutoLog(value = "体育赛项（团体）-编辑")
	@ApiOperation(value="体育赛项（团体）-编辑", notes="体育赛项（团体）-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody TysxPage tysxPage) {
		Tysx tysx = new Tysx();
		BeanUtils.copyProperties(tysxPage, tysx);
		Tysx tysxEntity = tysxService.getById(tysx.getId());
		if(tysxEntity==null) {
			return Result.error("未找到对应数据");
		}
		tysxService.updateMain(tysx, tysxPage.getMemberListList());
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "体育赛项（团体）-通过id删除")
	@ApiOperation(value="体育赛项（团体）-通过id删除", notes="体育赛项（团体）-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		tysxService.delMain(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "体育赛项（团体）-批量删除")
	@ApiOperation(value="体育赛项（团体）-批量删除", notes="体育赛项（团体）-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.tysxService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "体育赛项（团体）-通过id查询")
	@ApiOperation(value="体育赛项（团体）-通过id查询", notes="体育赛项（团体）-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		Tysx tysx = tysxService.getById(id);
		if(tysx==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(tysx);

	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "成员列表通过主表ID查询")
	@ApiOperation(value="成员列表主表ID查询", notes="成员列表-通主表ID查询")
	@GetMapping(value = "/queryMemberListByMainId")
	public Result<?> queryMemberListListByMainId(@RequestParam(name="id",required=true) String id) {
		List<MemberList> memberListList = memberListService.selectByItemId(id);
		return Result.OK(memberListList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param tysx
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Tysx tysx)throws NoSuchFieldException{

		try{
			String rolesStr = GfxyUtils.getRoles(request);
			String date = tysx.getDate();
			List<TysxMemberPage> tysxMemberPages = tysxService.getTysxMemberPageListByYear(date);

			List<String> title = new ArrayList<>();
			title.add("积分时间");
			title.add("级别");
			title.add("奖项");
			title.add("体育赛项");
			title.add("成员");

			List<List<String>> contents = new ArrayList<>();
			for (TysxMemberPage tysxMemberPage : tysxMemberPages) {
				List<String> content = new ArrayList<>();
				content.add(tysxMemberPage.getDate());
				content.add(dictTranslater.getDictValue(TysxMemberPage.class, "classess", String.valueOf(tysxMemberPage.getClassess())));
				content.add(dictTranslater.getDictValue(TysxMemberPage.class, "award", String.valueOf(tysxMemberPage.getClassess())));
				content.add(tysxMemberPage.getProjectName());

				List<MemberSimpleList> list = tysxMemberPage.getMemberListList();
				StringBuffer names = new StringBuffer();
				for (MemberSimpleList memberSimpleList : list) {
					names.append(memberSimpleList.getUserName()).append("、");
				}
				content.add(names.toString());
				contents.add(content);
			}


			ModelAndView mv = new ModelAndView(new TeachingExcelView());
			mv.addObject(TeachingExcelView.FILE_NAME,"体育赛项-" + date);
			mv.addObject(TeachingExcelView.TITLE, title);
			mv.addObject(TeachingExcelView.CONTENT, contents);
			return mv;
		} catch (Exception e){
			throw e;
		}


	}

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
			  Map<String,List<String>>  resultMap = new HashMap<>();
			  return Result.OK(tysxService.importExcel(file));
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }
	 @GetMapping(value = "/getTotalScore")
	 public Result<?> getTotalScore(@RequestParam(name="classess", defaultValue="0")  Integer classess,
									@RequestParam(name="award", defaultValue="0") Integer award,
									HttpServletRequest req) {
		 Tysx tysx = new Tysx();
		 tysx.setClassess(classess);
		 tysx.setAward(award);
		 Double result = this.tysxService.getTotalScore(tysx);
		 return Result.OK(result);
	 }
	 @GetMapping(value = "/handleExportXlsTemplate")
	 public Result<?> download(HttpServletRequest request, HttpServletResponse response)  {

		 try {
			 templateUtil.template(response,TemplateUtil.YTSX);
		 } catch (IOException e) {
			 e.printStackTrace();
			 return  Result.error("下载失败");
		 }
		 return  Result.OK("下载成功");
	 }
}
